import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;

/**
 * 
 */

/**
 * @author lucas
 *
 */
public class ComputeTCP extends Thread {

	private Environment _env; 

	public ComputeTCP(){
		_env = new Environment();
	}

	public ComputeTCP(Environment env){
		_env = env; 
	}


	private void runClientTCP() throws Exception
	{
		int sizeData = 10*Environment.KB64; 
		int size = _env.get_bufferSize();
		int nbSend = sizeData/size;
		
		Calendar begin, end; 
		
		byte toSend[] = new byte[size];
		byte toReceive[] = new byte[size];
		for (int i=0; i<size; i++){
			toSend[i] = (byte)42;
		}
		
		Socket clientSocket = new Socket(_env.get_loopbackAddr(), _env.get_port());
		
		
		begin= Calendar.getInstance();
		for (int i=0; i< nbSend; i++){
			DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
			DataInputStream inFromServer = new DataInputStream(clientSocket.getInputStream());
			
			outToServer.write(toSend, 0, size);
			outToServer.flush();
			inFromServer.read(toReceive);
		}
		end = Calendar.getInstance(); 
		clientSocket.close();
		
		float time = end.getTimeInMillis()-begin.getTimeInMillis();
		if (size == Environment.B){
			float latency = (20*Environment.KB64)/time;
			System.out.println("Latency : " + latency); 	
			System.err.println(latency+";");
		}
		float throughtput = ((float)20*(float)Environment.KB64/(float)Environment.MB);
		throughtput = throughtput /(time/1000);
		System.out.println("Total time in millisecond : " + time); 
		System.out.println("Throughtput : " + throughtput + " MB/s"); 
		System.err.println(";"+throughtput+";");

	}


	@Override
	public void run() {
		try {
			runClientTCP();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
